package com.funong.matrix.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.funong.matrix.core.enums.IsDeletedEnum;
import com.funong.matrix.core.enums.StatusEnum;
import com.funong.matrix.core.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * todo 统一将Date -> LocalDateTime
 * 实体字段自动填充处理类
 *
 * @author nanahou
 */
@Slf4j
@Component
public class FieldAutoFillHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        if (this.getFieldValByName("createdAt", metaObject) == null) {
            this.setInsertFieldValByName("createdAt", now, metaObject);
        }
        if (this.getFieldValByName("updatedAt", metaObject) == null) {
            this.setInsertFieldValByName("updatedAt", now, metaObject);
        }
        if (this.getFieldValByName("isDeleted", metaObject) == null) {
            this.setInsertFieldValByName("isDeleted", IsDeletedEnum.NOT_DELETED.getValue(), metaObject);
        }
        if (this.getFieldValByName("status", metaObject) == null) {
            this.setInsertFieldValByName("status", StatusEnum.ENABLE.getValue(), metaObject);
        }
        if (this.getFieldValByName("version", metaObject) == null) {
            this.setInsertFieldValByName("version", 0, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date now = DateTimeUtil.now();
        if (this.getFieldValByName("updatedAt", metaObject) == null) {
            this.setUpdateFieldValByName("updatedAt", now, metaObject);
        }
    }
}
